import { onUnmounted } from 'vue';
import { eventBus } from './eventBus';

export function useEvents() {
  // 存储移除监听的函数
  const unsubscribers: Function[] = [];
  
  // 监听全局事件（自动清理）
  const onGlobal = (event: string, handler: (payload: any) => void) => {
    eventBus.global.on(event, handler);
    unsubscribers.push(() => eventBus.global.off(event, handler));
  };
  
  // 触发全局事件
  const emitGlobal = (event: string, payload?: any) => {
    eventBus.global.emit(event, payload);
  };
  
  // 监听模块事件（自动清理）
  const onModule = (moduleId: string, event: string, handler: (payload: any) => void) => {
    const bus = eventBus.module(moduleId);
    bus.on(event, handler);
    unsubscribers.push(() => bus.off(event, handler));
  };
  
  // 触发模块事件
  const emitModule = (moduleId: string, event: string, payload?: any) => {
    eventBus.module(moduleId).emit(event, payload);
  };
  
  // 组件卸载时自动清理所有监听
  onUnmounted(() => {
    unsubscribers.forEach(unsub => unsub());
    unsubscribers.length = 0;
  });
  
  return {
    onGlobal,
    emitGlobal,
    onModule,
    emitModule
  };
}